package model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.logging.Logger;

public class Login {
	private static Logger theLogger = Logger.getLogger("Login");
	private String USERDATADIV = "-@#-";		

	public synchronized String validateUser(String user, String password, String login_type) {
		System.out.println("{validating user " + user + " with password " + password +"}");
		
		String result = "";
		
		if(user != null && password != null && login_type != null) {			
			String query = "SELECT id , first_name, last_name, status, user_level FROM ";
			if(login_type.equals("Student")) {
				query += " student "
					   + " WHERE BINARY roll_number = '" + user
					   + "' AND BINARY dob  =  '" + password + "'";
			} else if(login_type.equals("Administrator")) {
				query += " administrator "
						   + " WHERE BINARY code = '" + user
						   + "' AND BINARY password  =  '" + password + "'";
			} else if(login_type.equals("Evaluator")) {
				query += " evaluator "
						   + " WHERE BINARY code = '" + user
						   + "' AND BINARY password  =  '" + password + "'";
			} else {
				result = "Invalid";
				return result;
			}
			
			theLogger.info("query: " + query);
			
			try {
				DBAdapter_New adapter = DBAdapter_New.getInstance();
				adapter.open();
				ResultSet rs = adapter.select(query);
				int i=0;
				while(rs.next()){
					if(rs.getInt("status") == 0) {
						result = "Disabled";
					} else {
						int userId = rs.getInt("id");
						String firstName = rs.getString("first_name");
						String lastName = rs.getString("last_name");
						String dbIsEnabled = rs.getString("status");
						int userLevel = rs.getInt("user_level");
						
						result = userId + USERDATADIV + firstName + USERDATADIV + lastName + USERDATADIV + dbIsEnabled + USERDATADIV + userLevel;
					}
					i++;
				}
				if(i == 0) {
					result = "Invalid";
				}
				//System.out.println("validiateMessage: " + validateMessage);
				adapter.close();
			} catch(Exception ex) {
				//ex.printStackTrace();
			}
		} else {
			result = "Invalid";
		}
		return result;
	}
	
	/**
	 * 
	 * @return
	 */
	public HashMap<String, String> getStudentProgram(int student_id) {
		String query = "SELECT st.program_id , st.roll_number, pr.name FROM student st, program pr where "
				+ " st.id=" + student_id
				+ " and st.id= pr.id";
		HashMap<String, String> hashMap = new HashMap<>();
		try {
			DBAdapter_New adapter = DBAdapter_New.getInstance();
			adapter.open();
			ResultSet rs = adapter.select(query);
			if(rs.next()){
				hashMap.put("program_id", rs.getString(1));
				hashMap.put("Enrollment_Number", rs.getString(2));
				hashMap.put("program_name", rs.getString(3));
			}
			adapter.close();
		} catch(SQLException e) {
			e.printStackTrace();
		}
		
		return hashMap;
	}
}
